﻿namespace SADev.SharePointHolidayLoader
{
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using DevExpress.Xpf.Editors;
    using Microsoft.Win32;
    using Microsoft.WindowsAPICodePack.Dialogs;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectHolidayFileEvent(object sender, RoutedEventArgs e)
        {
            SelectHolidayFile(holidayFileTextEdit);
        }

        private static void SelectHolidayFile(TextEdit target)
        {
            var selectHolidayFileDialog = new OpenFileDialog
            {
                CheckFileExists = true,
                CheckPathExists = true,
                DefaultExt = "hol",
                Filter = "Holiday Files (*.hol)|*.hol|All Files (*.*)|*.*",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                Multiselect = false,
                ShowReadOnly = true
            };

            selectHolidayFileDialog.FileOk += (sender, e) =>
                {
                    target.Text = selectHolidayFileDialog.FileName;
                };

            selectHolidayFileDialog.ShowDialog();
        }

        private static void MissingInfoDialog(string message)
        {
            using (TaskDialog td = new TaskDialog()
                            {
                                Cancelable = true,
                                Caption = "Error",
                                Icon = TaskDialogStandardIcon.Error,
                                InstructionText = "Incomplete Information",
                                StandardButtons = TaskDialogStandardButtons.Ok,
                                Text = message
                            })
            {
                td.Show();
            }
        }
        private void PublishHolidayFileEvent(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(sharePointURITextEdit.Text))
            {
                MissingInfoDialog("SharePoint URI is missing");
                return;
            }

            if (string.IsNullOrWhiteSpace(calendarNameTextEdit.Text))
            {
                MissingInfoDialog("SharePoint Calendar name missing");
                return;
            }

            Uri sharePointUri;
            var uriTestResult = Uri.TryCreate(sharePointURITextEdit.Text, UriKind.Absolute, out sharePointUri);

            if (!uriTestResult)
            {
                MissingInfoDialog("SharePoint URI is invalid");
                return;
            }

            if (string.IsNullOrWhiteSpace(holidayFileTextEdit.Text) || !File.Exists(holidayFileTextEdit.Text))
            {
                MissingInfoDialog("Calendar file missing");
                return;
            }

            if (!string.IsNullOrWhiteSpace(usernameTextEdit.Text) || !string.IsNullOrWhiteSpace(passwordTextEdit.Text) || !string.IsNullOrWhiteSpace(domainTextEdit.Text))
            {
                if (string.IsNullOrWhiteSpace(usernameTextEdit.Text) || string.IsNullOrWhiteSpace(passwordTextEdit.Text))
                {
                    MissingInfoDialog("You have supplied some of the credential information, but not all of it.");
                    return;
                }
            }
            
            NetworkCredential credential = null;
            if (!string.IsNullOrWhiteSpace(usernameTextEdit.Text) ||
                !string.IsNullOrWhiteSpace(passwordTextEdit.Text) ||
                !string.IsNullOrWhiteSpace(domainTextEdit.Text))
            {
                if (!string.IsNullOrWhiteSpace(domainTextEdit.Text))
                {
                    credential = new NetworkCredential(usernameTextEdit.Text, passwordTextEdit.Text, domainTextEdit.Text);
                }
                else
                {
                    credential = new NetworkCredential(usernameTextEdit.Text, passwordTextEdit.Text);
                }
            }

            PublishHolidayFile(holidayFileTextEdit.Text, sharePointUri, calendarNameTextEdit.Text, credential);
        }

        private static void PublishHolidayFile(string filename, Uri sharePointUri, string calendarName, NetworkCredential credential)
        {
            HolidayCalendar holidayCalendar = null;
            try
            {
                holidayCalendar = HolidayCalendar.Load(filename);
            }
            catch (Exception err)
            {
                var exceptionTaskDialog = new TaskDialog
                {
                    Cancelable = false,
                    Caption = "Error",
                    Icon = TaskDialogStandardIcon.Error,
                    StandardButtons = TaskDialogStandardButtons.Ok,
                    StartupLocation = TaskDialogStartupLocation.CenterOwner,
                    InstructionText = string.Format(CultureInfo.CurrentCulture, "An error occurred trying to publish calendar entries.{0}{1}", Environment.NewLine, err.Message),
                    DetailsExpanded = false,
                    DetailsExpandedText = err.StackTrace,
                };

                exceptionTaskDialog.Show();
                return;
            }

            string country = holidayCalendar.Countries[0].Name;
            if (holidayCalendar.Countries.Count() > 1)
            {
                var countries = from c in holidayCalendar.Countries
                                orderby c.Name
                                select c.Name;

                var countrySelectWindow = new SelectCountryWindow(countries);
                countrySelectWindow.ShowDialog();
                country = countrySelectWindow.SelectedCountry;
            }


            var progressBar = new TaskDialogProgressBar(0, holidayCalendar.Countries[country].Holidays.Count(), 0)
            {
                State = TaskDialogProgressBarState.Normal
            };

            var progressTaskDialog = new TaskDialog
            {
                Cancelable = false,
                Caption = "Loading...",
                StandardButtons = TaskDialogStandardButtons.None,
                StartupLocation = TaskDialogStartupLocation.CenterOwner,
                ProgressBar = progressBar
            };

            bool successful = false;

            progressTaskDialog.Opened += (sender, e) =>
                {
                    successful = holidayCalendar.Publish(sharePointUri, calendarName, credential, country, i => { progressBar.Value = i; });
                    progressTaskDialog.Close();
                    if (!successful)
                    {
                        var exceptionTaskDialog = new TaskDialog
                                              {
                                                  Cancelable = false,
                                                  Caption = "Error",
                                                  Icon = TaskDialogStandardIcon.Error,
                                                  StandardButtons = TaskDialogStandardButtons.Ok,
                                                  StartupLocation = TaskDialogStartupLocation.CenterOwner,
                                                  InstructionText = string.Format(CultureInfo.CurrentCulture, "An error occurred trying to publish calendar entries.{0}{1}", Environment.NewLine, holidayCalendar.LastException.Message),
                                                  DetailsExpanded = false,
                                                  DetailsExpandedText = holidayCalendar.LastException.StackTrace,
                                              };

                        exceptionTaskDialog.Show();
                    }
                };

            progressTaskDialog.Show();

            if (successful)
            {
                var doneTaskDialog = new TaskDialog
                {
                    Cancelable = false,
                    Caption = "Done",
                    StandardButtons = TaskDialogStandardButtons.Ok,
                    StartupLocation = TaskDialogStartupLocation.CenterOwner,
                    InstructionText = "Completed import"
                };

                doneTaskDialog.Show();
            }
        }

        private void QuitApplicationEvent(object sender, RoutedEventArgs e)
        {
            QuitApplication();
        }

        private void QuitApplication()
        {
            this.Close();
        }

        private void MoreInfoEvent(object sender, RoutedEventArgs e)
        {
            MoreInfo();
        }

        private static void MoreInfo()
        {
            Process.Start("http://shl.codeplex.com");
        }


    }
}
